package com.powernode.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.powernode.domain.ProdProp;
import com.powernode.domain.ProdPropValue;
import com.powernode.mapper.ProdPropMapper;
import com.powernode.mapper.ProdPropValueMapper;
import com.powernode.service.ProdPropService;
import com.powernode.service.ProdPropValueService;
import com.powernode.utils.AuthUtil;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.units.qual.K;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 内容:
 * 作者: cy
 */
@Service
@Slf4j
@CacheConfig(cacheNames = "com.powernode.service.impl.ProdPropServiceImpl")
public class ProdPropServiceImpl extends ServiceImpl<ProdPropMapper, ProdProp> implements ProdPropService {

    @Autowired
    private ProdPropMapper prodPropMapper;

    @Autowired
    private ProdPropValueMapper prodPropValueMapper;

    @Autowired
    private ProdPropValueService prodPropValueService;


    /**
     * 分页查询属性列表
     * 1.先分页查询属性
     * 2.在查询属性值
     * 3.把属性值的集合放在属性对象中
     *
     * @param page
     * @param prodProp
     * @return
     */
    @Override
    public Page<ProdProp> selectProdPropPage(Page<ProdProp> page, ProdProp prodProp) {
        Long shopId = AuthUtil.getUserIdOrShopId(false);
        // 分页查询属性
        Page<ProdProp> prodPropPage = prodPropMapper.selectPage(page, new LambdaQueryWrapper<ProdProp>()
                .eq(ProdProp::getShopId, shopId)
                .like(StringUtils.hasText(prodProp.getPropName()), ProdProp::getPropName, prodProp.getPropName())
        );
        List<ProdProp> propList = prodPropPage.getRecords();
        if (CollectionUtils.isEmpty(propList)) {
            return prodPropPage;
        }
        // 拿属性的ids
        List<Long> propIds = propList.stream()
                .map(ProdProp::getPropId)
                .collect(Collectors.toList());
        // 查属性值表  in
        List<ProdPropValue> prodPropValues = prodPropValueMapper.selectList(new LambdaQueryWrapper<ProdPropValue>()
                .in(ProdPropValue::getPropId, propIds)
        );
        // 循环 属性集合 过滤出符合的属性值 设置
        // 1 ，2   111 112    113  114
        propList.forEach(prodProp1 -> {
            List<ProdPropValue> propValueList = prodPropValues.stream()
                    .filter(prodPropValue -> prodPropValue.getPropId().equals(prodProp1.getPropId()))
                    .collect(Collectors.toList());
            prodProp1.setProdPropValues(propValueList);
        });
        return prodPropPage;
    }

    /**
     * 新增属性和属性值
     *
     * @param prodProp
     */
    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    @CacheEvict(key = "#prodProp.shopId")
    public void savePropProdAndValues(ProdProp prodProp) {
        Long userId = AuthUtil.getUserIdOrShopId(true);
        log.info("新增属性和属性值{}，用户id为{}，店铺id为{}", JSON.toJSONString(prodProp), userId, prodProp.getShopId());
        prodProp.setRule(1);
        int i = prodPropMapper.insert(prodProp);
        if (i > 0) {
            // 写属性值的表
            List<ProdPropValue> prodPropValues = prodProp.getProdPropValues();
            prodPropValues.forEach(prodPropValue -> {
                prodPropValue.setPropId(prodProp.getPropId());
            });
            // 批量插入
            prodPropValueService.saveBatch(prodPropValues);
        }
    }


    /**
     * 查询当前店铺的所有属性集合
     *
     * @param shopId
     * @return
     */
    @Override
    @Cacheable(key = "#shopId")
    public List<ProdProp> selectShopProdProp(Long shopId) {
        return prodPropMapper.selectList(new LambdaQueryWrapper<ProdProp>()
                .eq(ProdProp::getShopId, shopId)
        );
    }
}
